import { Disposable } from "ol";
import { length, normalize, sub, scale, add } from "./vector"
export default class LineMotion {
    constructor(points, speed) {
        this.points = points;
        this.speed = speed || 0;
        this.index = 0;
        this.curVecRemain = 0;
        this.lastPos = this.points[0];
    }

    update(dt) {
        if (!this.points || this.points.length < 2 || !this.speed) {
            return null;
        }

        /**剩下需要移动的距离 */
        let distance = this.speed * dt;
        /**当前向量 */
        let curVec = [];
        /**当前向量长度 */
        let curLen = 0;
        do {
            curVec = sub(this.points[this.index + 1], this.points[this.index]);
            curLen = this.curVecRemain || length(curVec);

            if (curLen > distance) { //当前向量的长度足够此次移动的距离
                //记录剩下距离以便下一帧使用
                this.curVecRemain = curLen - distance;
                curLen = distance;
                break;
            } else { //当前向量长度不足此次移动的距离
                distance -= curLen;
                this.index++;
                if (this.index >= this.points.length - 1) {
                    this.index = 0;
                }
                this.curVecRemain = 0;
                this.lastPos = this.points[this.index];
            }
        } while (distance > 0);

        const dir = Object.assign([], normalize(curVec, curVec));
        scale(curVec, curLen, curVec);
        add(curVec, this.lastPos, curVec);
        this.lastPos = curVec;
        return {
            pos: curVec,
            dir: dir
        }
    }
}